package com.dashan.looperpager.card;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.cardview.widget.CardView;
import androidx.viewpager.widget.PagerAdapter;

import com.dashan.looperpager.R;

import java.util.ArrayList;
import java.util.List;


public class CardPagerAdapter extends PagerAdapter implements CardAdapter {

    private List<CardView> mViews;
    private List<Integer> mData;

    private int MaxElevationFactor = 9;

    @Override
    public int getMaxElevationFactor() {
        return MaxElevationFactor;
    }

    @Override
    public void setMaxElevationFactor(int MaxElevationFactor) {
        this.MaxElevationFactor = MaxElevationFactor;
    }

    public CardPagerAdapter() {
        mData = new ArrayList<>();
        mViews = new ArrayList<>();
    }

    public void addImgUrlList(List<Integer> imgUrlList) {
        mData.addAll(imgUrlList);
        for (int i = 0; i < imgUrlList.size(); i++) {
            mViews.add(null);
        }
    }


    @Override
    public CardView getCardViewAt(int position) {
        int realPosition = position % mViews.size();
        return mViews.get(realPosition);
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : 100;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        int realPosition = position % mData.size();
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.adapter, container, false);
        container.addView(view);
        ImageView iv = view.findViewById(R.id.item_iv);
        iv.setImageResource(mData.get(realPosition));
        CardView cardView = view.findViewById(R.id.cardView_adapter);
        cardView.setMaxCardElevation(MaxElevationFactor);
        mViews.set(realPosition, cardView);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        int realPosition = position % mViews.size();
        mViews.set(realPosition, null);
    }

    /**
     * 返回mData真正的大小
     */
    public int getDataRealSize() {
        return mData == null ? 0 : mData.size();
    }

}
